/*
 * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.demo.config.security.login.sms;
import java.time.LocalDateTime;
import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.bean.User;
import com.example.demo.config.security.LoginUser;
import com.example.demo.service.MyUserService;
import jakarta.servlet.http.HttpSession;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * An {@link AuthenticationProvider} implementation that retrieves user details from a
 * {@link UserDetailsService}.
 *
 * @author Ben Alex
 * @author Rob Winch
 */
public class SmsAuthenticationProvider extends SmsAbstractUserDetailsAuthenticationProvider {

	/**
	 * The plaintext password used to perform
	 * {@link PasswordEncoder#matches(CharSequence, String)} on when the user is not found
	 * to avoid SEC-2056.
	 */
	private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";

	private PasswordEncoder passwordEncoder;

	/**
	 * The password used to perform {@link PasswordEncoder#matches(CharSequence, String)}
	 * on when the user is not found to avoid SEC-2056. This is necessary, because some
	 * {@link PasswordEncoder} implementations will short circuit if the password is not
	 * in a valid format.
	 */
	private volatile String userNotFoundEncodedPassword;

	@Getter
	@Setter
	private UserDetailsService myUserService;

	private UserDetailsPasswordService userDetailsPasswordService;

	public SmsAuthenticationProvider() {
		setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
	}
	@Override
	public boolean supports(Class<?> authentication) {
		return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
	}

	/**
	 * 如果是usernamepassword的那个 ，这个方法就是用来做密码匹配的
	 * 现在是短信登陆 ，则可以进行验证码校验
	 * @param userDetails as retrieved from the
	 * {@link #retrieveUser(String, SmsAuthenticationToken)} or
	 * <code>UserCache</code>
	 * @param authentication the current request that needs to be authenticated
	 * @throws AuthenticationException
	 */
	@Override
	@SuppressWarnings("deprecation")
	@Transactional(rollbackFor = Exception.class)
	protected UserDetails additionalAuthenticationChecks(UserDetails userDetails,
			SmsAuthenticationToken authentication) throws AuthenticationException {

		//todo 对于在这个方法进行验证验证码表示疑问，后续进行排查
		if (authentication.getCredentials() == null) {
			this.logger.debug("Failed to authenticate since no credentials provided");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpSession session = servletRequestAttributes.getRequest().getSession();
		String phone = authentication.getPrincipal().toString();
		//去session拿到之前验证码接口存入的code
		String sessionCode = (String) session.getAttribute(phone);
		//用户传进来验证码
		String code = authentication.getCredentials().toString();
		if (!code.equalsIgnoreCase(sessionCode)) {
			throw new BadCredentialsException("验证码输入错误");
		}

		User user = null;
		MyUserService userService = null;
		if (myUserService instanceof MyUserService){
			userService = (MyUserService) this.myUserService;
			user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, phone));
		}
		if (user == null) {
			user = new User();
//			user.setUsername("");
//			user.setPassword("");
			user.setEnabled(true);
			user.setAccountNonExpired(true);
			user.setAccountNonLocked(true);
			user.setCredentialsNonExpired(true);
			user.setPhone(phone);
			user.setLastLoginTime(LocalDateTime.now());

			//调用者的userDetails是空
			LoginUser loginUser = new LoginUser();
			loginUser.setUser(user);
			userDetails = loginUser;
		}else {
			user.setLastLoginTime(LocalDateTime.now());
		}
		userService.saveOrUpdate(user);
		return userDetails;
	}

	@Override
	protected void doAfterPropertiesSet() {
		Assert.notNull(this.myUserService, "A myUserService must be set");
	}

	/**
	 * 手机号查询用户的
	 * @param phone The username to retrieve
	 * @param authentication The authentication request, which subclasses <em>may</em>
	 * need to perform a binding-based retrieval of the <code>UserDetails</code>
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected final UserDetails retrieveUser(String phone, SmsAuthenticationToken authentication)
			throws AuthenticationException {
		prepareTimingAttackProtection();
		UserDetails loadedUser = null;
		if (myUserService instanceof MyUserService){
			MyUserService userService = (MyUserService) this.myUserService;
			loadedUser = userService.loadUserByPhone(authentication.getPrincipal().toString());
		}
		return loadedUser;
	}

	@Override
	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
			UserDetails user) {
		return super.createSuccessAuthentication(principal, authentication, user);
	}

	private void prepareTimingAttackProtection() {
		if (this.userNotFoundEncodedPassword == null) {
			this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
		}
	}

	private void mitigateAgainstTimingAttack(SmsAuthenticationToken authentication) {
		if (authentication.getCredentials() != null) {
			String presentedPassword = authentication.getCredentials().toString();
			this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
		}
	}

	/**
	 * Sets the PasswordEncoder instance to be used to encode and validate passwords. If
	 * not set, the password will be compared using
	 * {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}
	 * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder}
	 * types.
	 */
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
		this.passwordEncoder = passwordEncoder;
		this.userNotFoundEncodedPassword = null;
	}

	protected PasswordEncoder getPasswordEncoder() {
		return this.passwordEncoder;
	}


	public void setUserDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService) {
		this.userDetailsPasswordService = userDetailsPasswordService;
	}

}
